import datetime

from flask import jsonify, request

from db.dao import StockHoldersDao, HoldersRecordDao, StockOptionalDao
from db.models import StockHolders, HoldersRecord, StockOptional
from utils.util import FlaskTool, StockTool, CommonUtil
from web import custom


@custom.route('/holder/query-list')
def holder_list():
    '''
    持股列表
    :return:
    '''
    pagination = StockHoldersDao().queryByPage(request.args)
    return jsonify(FlaskTool.paginatioToList(pagination))


@custom.route('/holder/buy-stock', methods=['POST'])
def buy_stock():
    '''
    买入股票信息(后台强制新增通道)
    :return:
    '''
    # 保存持股信息
    stock_code = request.form.get('stock_code')
    stock_name = request.form.get("stock_name")
    buy_price = request.form.get('buy_price')
    buy_nums = request.form.get('buy_nums')
    buy_time = request.form.get('buy_time')

    handle_amount = buy_nums * buy_price

    stockHolders = StockHolders()
    setattr(stockHolders, 'stock_code', stock_code)
    setattr(stockHolders, 'stock_name', stock_name)

    existHolder = StockHoldersDao.queryByStockCode(stock_code)
    if existHolder:
        # 更新
        holder_code = getattr(existHolder, 'holder_code')
        existPrice = getattr(existHolder, 'average_price')
        existNums = getattr(existPrice, 'cur_nums')
        cur_nums = buy_nums + existNums
        ave_price = (existPrice * existNums + handle_amount) / cur_nums
        setattr(stockHolders, 'id', getattr(existHolder, 'id'))
    else:
        # 新增
        holder_code = CommonUtil.get_uuid()
        setattr(stockHolders, 'holder_code', holder_code)
        setattr(stockHolders, 'buy_time', buy_time)
        setattr(stockHolders, 'market', StockTool.code2Market(request.form.get('stock_code')))
        cur_nums = buy_nums
        ave_price = buy_price

    setattr(stockHolders, 'average_price', ave_price)
    setattr(stockHolders, 'cur_nums', cur_nums)
    StockHoldersDao().saveOrUpdate(stockHolders)

    # 保存持股记录

    holders_record = HoldersRecord()
    setattr(holders_record, 'holder_code', holder_code)
    setattr(holders_record, 'stock_name', stock_name)
    setattr(holders_record, 'stock_code', stock_code)
    setattr(holders_record, 'handle_nums', buy_nums)
    setattr(holders_record, 'handle_price', buy_price)
    setattr(holders_record, 'handle_amount', handle_amount)
    setattr(holders_record, 'remain_nums', cur_nums)
    setattr(holders_record, 'handle_time', buy_time)

    HoldersRecordDao().save(holders_record)
    return 'ok'


@custom.route('/holder/sell-stock', methods=['POST'])
def sell_stock():
    '''
    卖出股票信息
    :return:
    '''

    # 保存持股信息
    stock_code = request.form.get('stock_code')
    stock_name = request.form.get("stock_name")
    sell_price = request.form.get('sell_price')
    sell_nums = request.form.get('sell_nums')
    sell_time = datetime.datetime.now()

    handle_amount = sell_nums * sell_price

    existHolder = StockHoldersDao.queryByStockCode(stock_code)
    if not existHolder:
        # 不存在就返回 todo 异常
        return '不存在'

    holder_code = getattr(existHolder, 'holder_code')
    existPrice = getattr(existHolder, 'average_price')
    existNums = getattr(existPrice, 'cur_nums')
    if sell_nums > existNums:
        # 超卖
        return '超卖'
    elif sell_nums == existNums:
        StockHoldersDao().removeById(getattr(existHolder, 'id'))
        cur_nums = 0
        # 将自选股里的持有状态更新
        stockOptional = StockOptional()
        setattr(stockOptional, 'stock_code', stock_code)
        setattr(stockOptional, 'hold_state', 0)
        StockOptionalDao().saveOrUpdate(stockOptional)

    else:
        cur_nums = existNums - sell_nums
        setattr(existHolder, 'cur_nums', cur_nums)
        StockHoldersDao().saveOrUpdate(existHolder)

    # 保存持股记录

    holders_record = HoldersRecord()
    setattr(holders_record, 'holder_code', holder_code)
    setattr(holders_record, 'stock_name', stock_name)
    setattr(holders_record, 'stock_code', stock_code)
    setattr(holders_record, 'handle_nums', sell_nums)
    setattr(holders_record, 'handle_price', sell_price)
    setattr(holders_record, 'handle_amount', handle_amount)
    setattr(holders_record, 'remain_nums', cur_nums)
    setattr(holders_record, 'handle_time', sell_time)

    HoldersRecordDao().save(holders_record)

    return 'ok'
